package com.yanyu.space.sys.controller;


import com.yanyu.space.common.core.bean.db.PageEntity;
import com.yanyu.space.common.core.bean.web.R;
import com.yanyu.space.sys.bean.po.Role;
import com.yanyu.space.sys.bean.po.User;
import com.yanyu.space.sys.bean.vo.user.*;
import com.yanyu.space.sys.service.IRoleService;
import com.yanyu.space.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统用户 前端控制器
 *
 * @author yanyu
 */
@AllArgsConstructor
@Api(tags = "系统用户")
@RestController
@RequestMapping("/sys/user")
@Validated
public class UserController {

    private IUserService userService;
    private IRoleService roleService;

    @GetMapping("/list")
    @ApiOperation(value = "查询用户")
    public R<PageEntity<UserInfoVo>> list(UserSearchVo vo) {
        PageEntity<UserInfoVo> page = userService.listPage(vo);
        return R.ok(page);
    }

    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation(value = "根据id查询用户")
    public R<UserInfoVo> get(@PathVariable(value = "userId", required = false) Long userId) {
        return R.ok(userService.getById(userId));
    }

    @PostMapping
    @ApiOperation(value = "新增用户")
    public R add(@RequestBody UserAddVo vo) {
        userService.add(vo);
        return R.ok();
    }

    @PutMapping
    @ApiOperation(value = "修改用户")
    public R update(@RequestBody UserUpdateVo vo) {
        userService.updateById(vo);
        return R.ok();
    }

    @PutMapping("/changeStatus")
    @ApiOperation(value = "修改用户状态")
    public R changeStatus(@RequestBody UserUpdateVo vo) {
        userService.updateStatus(vo);
        return R.ok();
    }

    @PutMapping("/resetPwd")
    @ApiOperation(value = "修改用户状态")
    public R resetPwd(@RequestBody UserResetPwdVo vo) {
        userService.resetPwd(vo);
        return R.ok();
    }

    @DeleteMapping("/{ids}")
    @ApiOperation(value = "修改用户状态")
    public R delete(@PathVariable("ids") List<Long> ids) {
        userService.deleteById(ids);
        return R.ok();
    }

    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "查询用户关联的角色")
    public R listAuthRole(@PathVariable("userId") Long userId, User user) {
        PageEntity<Role> rolePageEntity = roleService.listAllocated(userId, user);
        return R.newMap().put("roles", rolePageEntity.getRows()).put("user", userService.getById(userId)).build();
    }

    @PutMapping("/authRole")
    @ApiOperation(value = "用户关联的角色")
    public R addAuthRole(@RequestParam("userId") Long userId, @RequestParam("roleIds") List<Long> roleIds) {
        userService.addAllocatedRole(userId, roleIds);
        return R.ok();
    }
}

